using System;
using System.Collections.Generic;
using System.Text;
using Petra.Gis.Geometry;
using Petra.Gis.Geometry.Support;

namespace Petra.Gis.DataServices.GDO
{
  public unsafe partial class GeometryFactory
  {
    /***********************************************
    * 28.8.2007
    * 
    * creates Polygon
    * from intergraph blob structure
    * 
    * asida@centrum.cz, initial implementation
    *************************************************/
    private static GeometryBase binaryToLineRing(byte[] vData, int arrayOffset, System.Type parentGeomType)
    {
      //if pure GDO.Polygon, must create Geometry.Polygon type
      //and put this GDO.Polygon inside !!
      if (parentGeomType == null || parentGeomType == typeof(GeometryCollection)) {
        Polygon oGeom = new Polygon();
        LineRing oGeominside = (LineRing)binaryToLineRing(vData, arrayOffset, typeof(Polygon));
        oGeom.Add(oGeominside);
        return oGeom;
      }

      //otherwise create pure LineRing
      CoordinateList Coords;
      LineRing oGeomLineRing = new LineRing();
      //int pocet;

      fixed (byte* bCoordListPtr = &vData[arrayOffset + 16])
      {
        int* lNumPoints = (Int32*)bCoordListPtr;
        //pocet = *lNumPoints;
        Coords = new CoordinateList(vData, arrayOffset + 20, *lNumPoints, Dimension.dim3D);
      }
      oGeomLineRing.coordList = Coords;

      return oGeomLineRing;
    }





    /***********************************************
    * 28.8.2007
    * 
    * creates intergraph blob structure 
    * from Polygon
    * 
    * asida@centrum.cz, initial implementation
    *************************************************/
    private static byte[] LineRingToBinary(GeometryBase geometry)
    {
      int lBlobSize;
      Guid gGeomGUID;

      //resolve polygon type, below code works only with single LineRing !!!
      LineRing _polygon = (LineRing)geometry;

      lBlobSize = 16 + 4 + (_polygon.coordList.Count * 24);

      System.IO.MemoryStream oIMStream = new System.IO.MemoryStream(lBlobSize);
      System.IO.BinaryWriter mBWriter = new System.IO.BinaryWriter(oIMStream);

      oIMStream.Position = 0;
      gGeomGUID = getGuid[GeometryType.Polygon];
      mBWriter.Write(gGeomGUID.ToByteArray());
      //todo:ensure int32 for 64bit platform !!!
      mBWriter.Write((Int32)_polygon.coordList.Count);
      mBWriter.Write(_polygon.coordList.ToArray(Dimension.dim3D));

      return oIMStream.ToArray();
    }
  }
}
